package han.cirno.corrupt.modules.exam

import androidx.activity.compose.LocalActivity
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import han.cirno.corrupt.compose.localeStringResource
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import han.cirno.corrupt.R
import han.cirno.corrupt.activity.main.MainActivityViewModel
import han.cirno.corrupt.compose.QuickOutlinedCard
import han.cirno.corrupt.compose.TextWithIcon
import han.cirno.corrupt.compose.VerticalSpacer
import han.cirno.corrupt.data.instances.UserExamData
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch

@Composable
fun ExamLayout(){
    val scope= rememberCoroutineScope()
    var currentTime by remember { mutableLongStateOf(System.currentTimeMillis()) }
    val mainActivityViewModel:MainActivityViewModel= hiltViewModel(LocalActivity.current as AppCompatActivity)
    DisposableEffect(Unit) {
        val job = scope.launch(Dispatchers.Default) {
            while (isActive) {
                currentTime = System.currentTimeMillis()
                delay(1000L)
            }
        }
        onDispose { job.cancel() }
    }
    val exams by mainActivityViewModel.allExamsFlow.collectAsState()
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(horizontal = 16.dp)
            .verticalScroll(rememberScrollState())) {
        VerticalSpacer(8.dp)
        exams.forEach{exam-> SingleExamCard(currentTime, exam) }
        VerticalSpacer(8.dp)
    }
}

@Composable
fun SingleExamCard(currentTime:Long,exam: UserExamData.Exam)=
    QuickOutlinedCard {
        Column {
            val notDeclared = localeStringResource(R.string.exam_notSpecified)
            Text(text = exam.name, fontSize = MaterialTheme.typography.titleMedium.fontSize)
            VerticalSpacer(4.dp)
            TextWithIcon(
                iconRes = R.drawable.baseline_calendar_month_24,
                text = if(exam.isDateUndeclared)
                    notDeclared
                else
                    exam.date.run { "$first/$second/$third" })
            TextWithIcon(
                iconRes = R.drawable.baseline_timelapse_24,
                text =
                if (exam.isTimeUndeclared)
                    notDeclared
                else
                    exam.fromTime.run {
                        "%02d:%02d".format(
                            first.toInt(),
                            second.toInt()
                        )
                    } + "-" + exam.toTime.run
                    { "%02d:%02d".format(first.toInt(), second.toInt()) })
            TextWithIcon(
                iconRes = R.drawable.baseline_place_24,
                text = if (exam.isPlaceUndeclared) notDeclared else "${exam.regionAndPlace}-${exam.seat}"
            )
            val (show, text, icon) = getExamUIInfo(currentTime, exam)
            AnimatedVisibility(visible = show) {
                TextWithIcon(
                    iconRes = icon,
                    text = text
                )
            }
        }
    }

@Composable
private fun getExamUIInfo(now:Long, exam: UserExamData.Exam):Triple<Boolean,String,Int>{
    val (timeState, timeLeftDay, timeLeftHour, timeLeftMinute, timeLeftSecond) = exam.getTimeDelta(now)
    return when(timeState){
        UserExamData.Exam.TimeState.Unspecified->Triple(false,"",0)
        UserExamData.Exam.TimeState.Coming->
            Triple(true, localeStringResource(R.string.exam_startAfter,
                timeLeftDay, timeLeftHour, timeLeftMinute, timeLeftSecond),R.drawable.baseline_access_time_24)
        UserExamData.Exam.TimeState.Progressing->Triple(
            true,localeStringResource(R.string.exam_inProgress,
                timeLeftHour, timeLeftMinute, timeLeftSecond),
            R.drawable.baseline_more_horiz_24)
        UserExamData.Exam.TimeState.End->
            Triple(true, localeStringResource(R.string.exam_finished),R.drawable.baseline_check_24_green)
    }
}
